package com.hjw.logtest1.controller;


import com.hjw.logtest1.entity.User;
import com.hjw.logtest1.error.BusinessException;
import com.hjw.logtest1.error.EmBusinessError;
import com.hjw.logtest1.model.UserModel;
import com.hjw.logtest1.paramobject.UserAddPO;
import com.hjw.logtest1.paramobject.UserIdPO;
import com.hjw.logtest1.response.CommonReturnType;
import com.hjw.logtest1.service.UserService;
import com.hjw.logtest1.viewobject.UserVO;
import org.springframework.beans.BeanUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author Hjw
 * @since 2023-04-07
 */
@RestController
@RequestMapping("/user")
public class UserController {

    private final UserService userService;

    public UserController(UserService userService) {
        this.userService = userService;
    }

    @PostMapping("/add")
    public CommonReturnType add(@RequestBody @Validated UserAddPO po) throws BusinessException {
        User user = new User();
        BeanUtils.copyProperties(po, user);
        boolean b = userService.save(user);
        if (!b) {
            throw new BusinessException(EmBusinessError.USER_ERROR, "新增用户错误");
        }
        return CommonReturnType.success();
    }

    @PostMapping("/del")
    public CommonReturnType del(@RequestBody @Validated UserIdPO user) throws BusinessException {
        boolean b = userService.removeById(user.getUserId());
        if (!b) {
            throw new BusinessException(EmBusinessError.USER_ERROR, "删除用户错误");
        }
        return CommonReturnType.success();
    }

    @GetMapping("getById")
    public CommonReturnType getById(@Validated UserIdPO model) throws BusinessException {
        UserModel userModel = userService.getUserModel(model.getUserId());
        UserVO vo = convertModel2VO(userModel);
        return CommonReturnType.success(vo);
    }

    private UserVO convertModel2VO(UserModel userModel) throws BusinessException {
        if (userModel == null) {
            throw new BusinessException(EmBusinessError.USER_NOT_EXIST);
        }
        UserVO vo = new UserVO();
        BeanUtils.copyProperties(userModel, vo);
        return vo;
    }
}

